package com.xiaoyi.analyzer.group;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaoyi
 * @version 1.0.0
 * @createTime 2023-02-19 17:45:00
 */
public class CommonGroup implements GroupInterFace {
   private CommonGroup commonGroup;
   private final String groupKey;

    public CommonGroup(String groupKey) {
        this.groupKey = groupKey;
    }

    public CommonGroup getCommonGroup() {
        return commonGroup;
    }

    public void setCommonGroup(CommonGroup commonGroup) {
        this.commonGroup = commonGroup;
    }

    public String getGroupKey() {
        return groupKey;
    }

    @Override
    public Map<String, Object> group(List<Map<String, Object>> list) {
        Map<String, List<Map<String, Object>>> resMap = list.stream().collect(Collectors.groupingBy(i -> getKey((Map<String, Object>) i, groupKey)));
        Map<String, Object> res = new HashMap<>();
        if (Objects.isNull(commonGroup)){
            resMap.forEach((k,v)->{
                res.put(k,v);
            });
        }else{
            // 循环结果
            resMap.forEach((k,v)->{
                Map<String, Object> group = commonGroup.group(v);
                res.put(k,group);
            });
        }
       return res;
    }

    private static String  getKey(Map<String,Object> map ,String keyGroup) {
        return (String) map.get(keyGroup);
    }

}
